/**
 * Created by Oswald on 2016/12/8.
 */

var operate = -1;
var selectedId = -1;
var selectedPID = -1;

var signDivIndex = -1;
var updateDivIndex = -1;

var loadUrl = "EquipmentEdit.html";
var serviceUrl = "#";

var typeList = "";
var statusList = "";

var enteredData = "";

$(document).ready(function() {

    LoadEquipment();
    LoadType();
    LoadStatus()

    //搜索按钮事件
    $("#search").click(function(){
        var no=$("#equipmentNo").val();
        var name=$("#equipmentName").val();
        var model=$("#equipmentModel").val();
        var typeid=$("#EquipmengType option:selected").val();
        var statusid=$("#EquipmentStatus option:selected").val();

        var data = {'no':no,'name':name,'model':model,'typeid':typeid,'statusid':statusid};
        LoadEquipment(data);
    })

    //新增设备按钮事件
    $("#addEqm").click(function(){
        $("#AddOrEditEquipmentDiv").load(loadUrl,function(){
            serviceUrl = serverPath + 'equipments/add';
            operate = 1;

            $("#equipmenttype").append(typeList);
            $("#equipmentstatus").attr("disabled", true);
        })
        updateDivIndex = ShowLayer($("#AddOrEditEquipmentDiv"),"新增设备","375px","500px");
    })

    //修改设备按钮事件
    $("#updateEqm").click(function(){
        $("#AddOrEditEquipmentDiv").load(loadUrl,function(){
            serviceUrl = serverPath + 'equipments/update';
            operate = 2;

            $("#equipmenttype").append(typeList);
            $("#equipmentstatus").append(statusList);

            var selects = $('#equipmentTable').bootstrapTable('getSelections')[0];
            $('#equipmentno').val(selects.no);
            $('#equipmentname').val(selects.name);
            $('#equipmentmodel').val(selects.model);
            $('#equipmentbacord').val(selects.barcode);
            $('#equipmentproperty').val(selects.propertyDescription);
        })
        updateDivIndex = ShowLayer($("#AddOrEditEquipmentDiv"),"修改设备","375px","500px");
    })

    //失效按钮事件
    $("#invalidEqm").click(function(){
        operate = 3;
        serviceUrl = serverPath + 'equipments/invalid';
        CallSign(111);
    })

    //单击行触发的事件
    $('#equipmentTable').on('click-row.bs.table', function (e, row, element){
        //拿到行选中的数据
        selectedId = row["id"];
        selectedPID = row["property"];

        var status = row["statusName"];
        //设置按钮状态
        if (status == "停用")
        {
            $('#updateEqm').attr("disabled", true);
            $('#invalidEqm').attr("disabled", true);
        }else {
            $('#updateEqm').attr("disabled", false);
            $('#invalidEqm').attr("disabled", false);
        }
    });
})

//弹出层
function ShowLayer(showDiv, title,width,height) {
    var divIndex = layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
        // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
        type: 1,
        //动画
        anim: 0,
        //title ：String
        //title: ['文本', 'font-size:18px;']
        //title: false 不显示标题栏
        title: [title, 'font-size:18px;font-weight:bold;'],
        //是否固定弹出
        fix: false,
        //最大小化按钮
        maxmin: false,
        //控制点击弹层外区域关闭
        shadeClose: false,
        //窗口大小 area: ['400px', '500px'] or auto 自适应大小
        area: [width, height],
        //area: '350px',
        //iframe层的url
        //content: 'http://www.baidu.com',
        content: showDiv,
        //是否允许拉伸
        resize: false,
        //浏览器滚动条
        scrollbar: false,
        zIndex: layer.zIndex, //重点1
        end: function () {
            //alert("close");
            $("#child").remove();
        }
    });
    //alert('return');
    return divIndex;
};

//加载设备信息
function LoadEquipment(data){
    $('#updateEqm').attr("disabled", true);
    $('#invalidEqm').attr("disabled", true);

    var url = serverPath+"equipments/findAll";
    $.ajax({
        url: url,
        data:data,
        xhrFields:{ withCredentials:true},
        traditional: true,
        type:"get",
        dataType:"json",
        success: function(result){
            var data = result.data;
            $("#equipmentTable").bootstrapTable('load', data);
            $("#equipmentTable").tableHideCheckbox();
        },
        error:function(){
            alert("请求失败");
        },
    });
}

//初始化类型列表
function InitType(typeData){
    $.each(typeData,function(index,item){
        var id = item.id;
        var name = item.name;

        typeList +="<option value='"+id+"'>"+name+"</option>"
    })
    $("#EquipmengType").append(typeList);
}

//获取设备类型
function LoadType(){
    var url =serverPath+"equipmentType/find/type";
    $.ajax({
        url: url,
        xhrFields:{ withCredentials:true},
        traditional: true,
        type:"get",
        dataType:"json",
        success: function(result){
            InitType(result.data);
        },
        error:function(){
            alert("请求失败");
        },
    });
}

//初始化状态列表
function InitStatus(statusData){
    $.each(statusData,function(index,item){
        var id = item.id;
        var name = item.name;

        statusList +="<option value='"+id+"'>"+name+"</option>"
    })
    $("#EquipmentStatus").append(statusList);
}

//获取设备状态
function LoadStatus(){
    var url = serverPath+"equipmentStatus/find/status";
    $.ajax({
        url: url,
        xhrFields:{ withCredentials:true},
        traditional: true,
        type:"get",
        dataType:"json",
        success: function(result){
            InitStatus(result.data);
        },
        error:function(){
            alert("请求失败");
        },
    });
}

//设备失效
function InvalidEquipment(sdid){
    var data = {"id":selectedId,"sdid":sdid};
    var type = 'put';
    EquipmentService(serviceUrl,data,type);
}

//设备服务
function EquipmentService(url, data,type) {
    $.ajax({
        url: url,
        type: type,
        data: data,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        async: false,
        success: function (result) {
            var errCode = result.errorCode
            if(errCode == 0) {
                //alert("成功");
                AfterSignature();
            }
            else
            {
                layer.close(signDivIndex);
                layer.alert('失败：错误代码[' + errCode +']');
            }
        },
        error:function(){
            layer.close(signDivIndex);
            alert("失败");
        }
    });
    }

//保存按钮事件
function saveBtnClick(){
    CallSign(111);
}

//取消按钮事件
function cancelBtnClick(){
    layer.close(updateDivIndex);
}

//获取当前输入
function GetEnteredEquipment() {
    var newNo = $('#equipmentno').val();
    var newName = $('#equipmentname').val();
    var newModel = $('#equipmentmodel').val();
    var newTypeId = $('#equipmenttype option:selected').val();
    var newStatusId = $('#equipmentstatus option:selected').val();
    var newBarcode = $('#equipmentbacord').val();
    var newProperty = $('#equipmentproperty').val();

    enteredData = {"no":newNo,"name":newName,"model":newModel,"typeId":newTypeId,"propertyDescription":newProperty,"barcode":newBarcode,"statusId":newStatusId};
}

//添加设备
function AddEquipment(sdid){
    GetEnteredEquipment();
    enteredData["sdid"] = sdid;
    var type = 'post';
    EquipmentService(serviceUrl,enteredData,type);
}

//修改设备
function UpdateEquipment(sdid){
    GetEnteredEquipment();
    enteredData["sdid"] = sdid;
    enteredData["property"] =  selectedPID;
    alert(selectedPID);
    enteredData["id"] = selectedId;
    var type = 'put';
    EquipmentService(serviceUrl,enteredData,type);
}



//签名
function CallSign(signId) {
    var url = "Signature.html";
    $("#SignDiv").load(url, function () {
        SignLoad(signId, SignCallBack);
    });
    signDivIndex = ShowLayer($("#SignDiv"), '签名', '400px', '420px');
}

//回调
function SignCallBack(sdid) {
    if (operate == 1)
    {
        AddEquipment(sdid);
    }
    if(operate == 2)
    {
        UpdateEquipment(sdid);
    }
    if(operate == 3)
    {
        InvalidEquipment(sdid);
    }
}

//签名成功后事件
function AfterSignature() {
    layer.close(signDivIndex);
    if(operate == 1) {
        layer.close(updateDivIndex);
    }
    if(operate == 2){
        layer.close(updateDivIndex);
    }
    LoadEquipment();
}